<template>
  <van-field name="uploader" :required="required" :rules="rules">
    <template #input>
      <van-uploader
        :max-size="20000 * 1024"
        @oversize="onOversize"
        max-count="1"
        :after-read="onRead"
        :before-delete="onDel"
        :before-read="beforeRead"
        :readonly="readonly"
        :deletable="!readonly"
        v-model="uploader"
        slot="default"
      >
        <img
          v-show="isNoFiles"
          class="uploadImg"
          :src="uploadCoverImg"
          alt=""
        />
      </van-uploader>
    </template>
  </van-field>
</template>

<script>
import { Uploader } from 'vant';
// 身份证正反面、户口本专用附件上传组件 单张上传
import { mapGetters } from "vuex";
import { upload_file, get_files } from "@/api/user.js";
export default {
  name: "commonUpload",
  components: {
    'van-uploader':Uploader
  },
  props: {
    bizType: {
      require: false,
    },
    bizId: {
      require: false,
    },
    uploadCoverImg: {
      require: false,
      default: require("@/assets/images/idCard1.png"),
    },
    rules: {
      require: false,
    },
    // true只读  false可上传可删除
    readonly: {
      require: false,
      default: false,
    },
    required:{
      require: false,
    },
  },
  computed: {
    ...mapGetters(["fileUrl"]),
  },
  data() {
    return {
      isNoFiles: true,
      headerImage: null,
      fileType: "",
      uploader: [],
    };
  },
  created() {
    if (this.bizId) {
      this.loadFile();
    }
  },
  watch: {
    uploader() {
      if (this.uploader && this.uploader.length == 0) {
        this.isNoFiles = true;
      } else {
        this.isNoFiles = false;
      }
    },
  },
  methods: {
    onOversize(file) {
      console.log(file);
      this.$toast('文件大小不能超过 20M');
    },
    async beforeRead(file) {
      // this.isNoFiles = false;
      // return new Promise((resolve, reject) => {

      // if (file.type == "image/jpeg") {
      //   let img = new File(["foo"], "bar.jpg", {
      //     type: "image/jpeg",
      //   });
      //   resolve(img);
      // } else if (file.type == "image/png") {
      //   let img = new File(["foo"], "bar.png", {
      //     type: "image/jpeg",
      //   });
      //   resolve(img);
      // } else {
      //   this.$toast("请上传 jpg或png 格式图片");
      //   reject();
      // }
      // });
    },
    loadFile() {
      console.log(this.fileUrl);
      console.log("回显");
      let data = {
        bizId: this.bizId,
        bizType: this.bizType,
      };
      get_files(data).then((res) => {
        if (res.succeed) {
          for (let i = 0; i < res.data.length; i++) {
            res.data[i].url = this.fileUrl + res.data[i].url;
          }
          this.uploader = res.data;
          this.$emit("fileLoad", res.data);
        }
      });
    },
    onDel(val, index) {
      if (val.file) {
        this.$emit("delFile", val.file);
        this.uploader.splice(
          this.uploader.findIndex((item) => item.file === val.file),
          1
        );
      } else {
        this.$emit("delFile", val);
        this.uploader.splice(
          this.uploader.findIndex((item) => item.id === val.id),
          1
        );
      }
    },
    //将base64转换为文件
    dataURLtoFile(dataurl) {
      var arr = dataurl.split(",");
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], this.fileType, {
        type: "image/jpeg",
      });
    },
    // 处理图片
    imgPreview(file) {
      let self = this;
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return;
      if (/^image/.test(file.type)) {
        // 创建一个reader
        let reader = new FileReader();
        // 将图片2将转成 base64 格式
        reader.readAsDataURL(file);
        // 读取成功后的回调
        reader.onloadend = function () {
          let result = this.result;
          let img = new Image();
          img.src = result;
          self.headerImage = this.result;
          // self.postImg();
          let file2 = self.dataURLtoFile(self.headerImage);
          let data = new window.FormData();
          data.append("file", file2);

          self.uploader[self.uploader.length - 1].status = "uploading";
          self.uploader[self.uploader.length - 1].message = "上传中...";

          // let data = new FormData();
          // data.append("file", file.file);
          upload_file(data)
            .then((res) => {
              if (res.succeed) {
                self.$emit("uploadSuccess", res.data, self.bizType, file);
                self.uploader[self.uploader.length - 1].status = "done";
                // 这里需要看上传成功后this.uploader是否有值
              } else {
                self.uploader[self.uploader.length - 1].status = "failed";
                self.uploader[self.uploader.length - 1].message = "上传失败";
              }
            })
            .catch((err) => {
              self.uploader[self.uploader.length - 1].status = "failed";
              self.uploader[self.uploader.length - 1].message = "上传失败";
            });
        };
      }
    },

    onRead(file) {
      console.log(file);
      this.fileType = file.file.name;
      // 压缩图片
      this.imgPreview(file.file);
    },
  },
};
</script>
<style lang="less" scoped>
.van-uploader {
  width: 567px;
  height: 365px;
}
.uploadImg {
  width: 100%;
}
/deep/.van-uploader__preview {
  margin: 0px !important;
  width: 567px !important;
  height: 365px !important;
  display: flex;
  justify-content: center;
  align-items: center;
}
/deep/ .van-uploader__preview-image {
  width: 100%;
  height: 100%;
}
/deep/ .van-field__control--custom {
  justify-content: center;
}
/deep/ .van-field__error-message {
  text-align: center;
}
</style>